﻿using System.Collections.Generic;
using System.Linq;
using System.Windows.Controls;
using System.Xml;
using System.Xml.Linq;

namespace ComicTool.Drawing.Svg
{
    public class TextLine
    {
        private readonly TextInfo textInfo;
        private readonly List<TextSpan> textSpans = new List<TextSpan>();

        public TextLine(TextInfo textInfo, XElement nav)
        {
            this.textInfo = textInfo;
            this.textInfo.LoadInfo(nav.Attributes().ToList());

            //IFormatProvider format = System.Globalization.CultureInfo.InvariantCulture.NumberFormat;
            //  float x = float.Parse(nav.Attribute("x").Value), format);
            //  float y = float.Parse(nav.Attribute("y").Value, format);
            //Point p =  textInfo.group.Transform(new Point(x, y));

            List<XNode> nodes = nav.Nodes().ToList();
            for (int i = 0; i < nodes.Count; i++)
            {
                TextSpan span;
                switch (nodes[i].NodeType)
                {
                    case XmlNodeType.Element:
                        {
                            span = new TextSpan(textInfo.Clone(), nodes[i] as XElement, true, true);
                            textSpans.Add(span);
                        }
                        break;
                    case XmlNodeType.Text:
                        {
                            span = new TextSpan(textInfo.Clone(), (nodes[i] as XText).Value, i == 0, i == nodes.Count - 1);
                            textSpans.Add(span);
                        }
                        break;
                }
            }
        }

        public TextBlock Draw()
        {
            var block = new TextBlock();
            block.RenderTransform = textInfo.group;
            foreach (TextSpan span in textSpans)
            {
                block.Inlines.Add(span.Draw());
            }
            return block;
        }
    }
}
